<template>
  <div class="datetime">
    <!-- <div class="back" @click="back()">
      <i class="el-icon-back"></i>返回
    </div> -->
    <div class="fullcalendar">
      <div class="selectBox">
        <div class="selectMonth">
          <i class="el-icon-arrow-left" @click="leftDay(1)"></i>
          <el-date-picker
            v-model="selectDate"
            @change="changeDate(1)"
            :clearable="false"
            v-show="isMonth === 1"
            :format="'yyyy'"
            value-format="yyyy-MM"
            :type="'year'"
            >
          </el-date-picker>
          <el-date-picker
            v-model="selectDate"
            @change="changeDate(1)"
            v-show="isMonth !== 1"
            :clearable="false"
            :format="'yyyy-MM'"
            value-format="yyyy-MM"
            :type="'month'"
            >
          </el-date-picker>
          <i class="el-icon-arrow-right" @click="leftDay(2)"></i>
        </div>
        <!-- <el-input
          class="searchInput"
          placeholder="输入标题或备注，回车搜索"
          @keyup.enter.native="getAgriplanlist"
          v-model="search"
        >
          <i slot="suffix" @click="getAgriplanlist()" class="el-input__icon el-icon-search"></i>
        </el-input> -->
        <div class="monthDay">
          <span :class="isMonth === 0 && 'checkDayChange'" @click="changeDayAndMonth(0)">日</span>
          <span :class="isMonth === 1 && 'checkDayChange'" @click="changeDayAndMonth(1)">月</span>
        </div>
      </div>
      <FullCalendar ref="fullCalendar" :options="calendarOptions" v-if="isMonth === 0 && showFef">
        <template #dayHeaderContent="content">
          <div>{{ weekDow[content.dow] }}</div>
        </template>
        <template #eventContent="">
          <div class="eventContent divWidth"><span class="eventBorder"></span></div>
        </template>
        <template #dayCellContent="content">
          <div class="dayFlex">
            <div class="dayHeight" :class="clickDay === $moment(content.date).format('YYYY-MM-DD') && 'checkDay'">{{ $moment(content.date).format('D')}}</div>
            <!-- <div v-if="clickDay === $moment(content.date).format('YYYY-MM-DD')">
              <img src="@/assets/img/dayAdd.png" class="dayAdd" @click.stop="addDate(content)"/>
            </div> -->
          </div>
        </template>
        <!-- <template #moreLinkContent="content">
          <div class="greyColor">更多{{content.num}}个事项</div>
        </template> -->
      </FullCalendar>
      <div class="fullMonth" v-if="isMonth === 1">
        <el-row class="monthLine">
          <el-col class="monthText" :span="2" v-for="item in 12" :key="item">
            <span
              @click="nowMonthSelct = (item < 10 ? `0${item}` : item), changeMonth()"
              :class="{
                nowMonthHas: `${$moment(selectDate).format('YYYY')}-${item < 10 ? `0${item}` : item}` === $moment().format('YYYY-MM'),
                nowMonthSelct: nowMonthSelct === (item < 10 ? `0${item}` : item)
              }"
            >
              {{ item < 10 ? `0${item}` : item}}
            </span>
            <div class="eventContent">
              <span class="eventBorder" v-if="calendarOptions.events.find(row=> {
                return $moment(row.start).format('YYYY-MM') == `${$moment(selectDate).format('YYYY')}-${item < 10 ? `0${item}` : item}`
              }) ? calendarOptions.events.find(row=> {
                return $moment(row.start).format('YYYY-MM') == `${$moment(selectDate).format('YYYY')}-${item < 10 ? `0${item}` : item}`
              }).id : ''"></span>
            </div>
          </el-col>
        </el-row>
        <!-- <div class="monthTag">
          <div class="tagFlex" v-for="(item, index) in calendarOptions.events" :key="index">
            <div class="tagTime">{{ $moment(item.fisrtDay).format('YYYY年MM月DD日') }}</div>
            <div>
              <div class="tagTitle"><span></span>{{item.agriName}}</div>
              <div class="greyColor">{{ item.landName }}<span>{{ item.userName }}</span></div>
              <div class="greyColor">{{ item.remark }}</div>
            </div>
          </div>
        </div> -->
      </div>
    </div>
    <add ref="add"/>
    <!-- 当前日期数据 -->
    <!-- <el-dialog
      :visible.sync="dialogVisible"
      width="4rem"
      class="editClass"
      :show-close="false"
      :before-close="dialogBeforeClose"
      append-to-body
    >
      <template #title></template>
      <div>
        <div class="dayBottom">
          <div class="dayImg">
            <div class="dayHeight">{{ weekName[moreDate.week] }} <span>{{ $moment(moreDate.day).format('MM') }}</span></div>
            <div>
              <img src="@/assets/img/workAdd.png" @click.stop="addDate({ date: moreDate.day })"/>
            </div>
          </div>
          <img class="wordImg" src="@/assets/img/workClose.png" @click="dialogBeforeClose()"/>
        </div>
        <div class="eventContent mt15" v-for="(item, index) in moreList" :key="item.id" @click="showDetail({ event: { id: item.id } }, index)"><span class="eventBorder"></span>{{ item.agriName }}</div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogContent"
      width="4.5rem"
      class="editClass"
      :show-close="false"
      :before-close="dialogBeforeDetailClose"
      append-to-body
    >
      <template #title></template>
      <div class="dayDetailContent">
        <div class="dayDetail">
          <div class="dayImg">
            <div class="dayHeight">农事详情</div>
          </div>
          <div class="wordImg">
            <img src="@/assets/img/workEdit.png" @click.stop="editDate()"/>
            <img src="@/assets/img/workDel.png" @click.stop="addDel()"/>
            <img src="@/assets/img/workClose.png" @click="dialogBeforeDetailClose()"/>
          </div>
        </div>
        <div class="eventContent"><span class="eventBorder"></span>{{ detailContent.agriName }}</div>
        <div class="eventContent"><img src="@/assets/img/work0.png"/>{{ detailContent.startTime }}{{ detailContent.startTime === detailContent.endTime ? '' : ` - ${detailContent.endTime}`}}</div>
        <div class="eventContent"><img src="@/assets/img/work1.png"/>{{ detailContent.landName }}</div>
        <div class="eventContent"><img src="@/assets/img/work2.png"/>{{ detailContent.userName }}</div>
        <div class="eventContent"><img src="@/assets/img/work3.png"/>{{ detailContent.remark }}</div>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import zhCnLocale from '@fullcalendar/core/locales/zh-cn'
import add from './component/add' // 添加农事
import { getAgriplanListApi, getDetailById, deleteAgriplan } from '@/api/baseInfo'
export default {
  name: 'DateTime',
  components: {
    add,
    FullCalendar // make the <FullCalendar> tag available
  },
  data () {
    return {
      search: null,
      showFef: false,
      dialogVisible: false,
      dialogContent: false,
      clickDay: null,
      selectDate: new Date(),
      isMonth: 0,
      weekDow: {
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        0: '日'
      },
      calendarOptions: {
        plugins: [
          // 加载插件，V5采用插件模块方式加入
          dayGridPlugin,
          timeGridPlugin,
          interactionPlugin // needed for dateClick
        ],
        height: 310, // 日历高度
        // headerToolbar: {
        //   left: 'today,title,prev,next',
        //   center: '',
        //   right: 'timeGridDay,dayGridMonth'
        // },
        headerToolbar: {
          // 头部toolba
          left: '',
          center: '',
          right: ''
        },
        // buttonText: { today: '今', month: '月', day: '日' },
        handleWindowResize: true, // 随浏览器窗口变化
        initialView: 'dayGridMonth', // 初始化插件显示
        // initialDate:""//初始化日期
        // initialEvents: INITIAL_EVENTS, // alternatively, use the `events` setting to fetch from a feed
        // editable: true, //是否可编辑
        droppable: true, // 可拖拽的
        // timeZone: 'local',//采用时区
        selectable: true,
        // selectMirror: true,
        dayMaxEvents: true,
        // dayMaxEventRows: 4,
        // weekends: true, // 是否显示一周七天
        // select: this.handleDateSelect,
        // eventClick: this.handleEventClick, // 日程点击事件
        eventMouseEnter: this.handleEventMouseEnter, // 用户将鼠标悬停在事件上时触发
        // eventsSet: this.handleEvents,
        // dateClick: this.handleDateClick,//日期方格点击事件
        dateClick: this.dayClick,
        eventClick: this.eventClick, // 日程点击事件
        moreLinkClick: this.moreClick, // 查看更多
        moreLinkContent: (info) => {
          // return `更多${info.num}个事项`
        },
        locale: zhCnLocale,
        firstDay: '0', // 每周的第一天
        // nextDayThreshold: '01:00:00',
        events: [
          // 日程事件的json
          // {
          //   title: 'event1',
          //   id: 1,
          //   start: '2024-05-01'
          // },
          // {
          //   title: 'event2',
          //   start: '2024-05-05',
          //   end: '2024-05-08'
          // },
          // {
          //   title: 'event3',
          //   id: 1,
          //   start: '2024-05-07T12:30:00',
          //   allDay: false
          // },
          // {
          //   title: 'event3',
          //   id: 1,
          //   start: '2024-05-09T12:30:00',
          //   allDay: false
          // }
        ]
        // datesSet: this.handleDateSet,
        /* you can update a remote database when these fire:
        eventAdd:
        eventChange:
        eventRemove:
        */
      },
      detailContent: {},
      nowMonthSelct: null,
      moreDate: {
        week: null,
        day: null
      },
      weekName: {
        0: '日',
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六'
      },
      moreList: [],
      delIndex: 0,
      setTime: null
    }
  },
  mounted () {
    this.getAgriplanlist()
  },
  methods: {
    // 日月切换
    changeDayAndMonth (type) {
      this.isMonth = type
      if (type === 0) {
        this.getAgriplanlist()
        this.selectDate = `${this.$moment(this.selectDate).format('YYYY')}-${this.nowMonthSelct}`
        this.$nextTick(() => {
          // 切换调整有问题跳转日期 暂时这样
          this.changeDate()
        })
      } else {
        this.nowMonthSelct = this.$moment(this.selectDate).format('MM')
        this.getAgriplanlist()
      }
    },
    // 计划删除
    async addDel () {
      await this.$confirm(`<span class="mrGrey">请确认删除<span><span>${this.detailContent.agriName}</span>`, '删除农事日历', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
      deleteAgriplan({ ids: this.detailContent.id }).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.getAgriplanlist()
          this.dialogBeforeDetailClose()
          if (this.dialogVisible) {
            this.moreList.splice(this.delIndex, 1)
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    dialogBeforeClose () {
      this.dialogVisible = false
    },
    dialogBeforeDetailClose () {
      this.dialogContent = false
    },
    // 编辑
    editDate () {
      this.$refs.add.getData(this.detailContent, 1)
    },
    // 显示计划详情
    showDetail (content, index) {
      this.delIndex = index
      getDetailById({ id: content.event.id }).then(res => {
        this.$set(this, 'detailContent', { ...res.data })
        this.dialogContent = true
      })
    },
    // 计划数据
    async getAgriplanlist () {
      let startTime = null
      let endTime = null
      if (this.isMonth === 1) {
        startTime = `${this.$moment(this.selectDate).format('YYYY')}-${this.nowMonthSelct}-01`
        endTime = `${this.$moment(this.selectDate).format('YYYY')}-${this.nowMonthSelct}-${this.$moment(this.nowMonthSelct).daysInMonth()}`
      }
      this.showFef = false
      await getAgriplanListApi({ remark: this.search, startTime: startTime, endTime: endTime, baseId: this.$store.getters.userInfo.baseId }).then(res => {
        this.$set(this.calendarOptions, 'events', [])
        res.data.map(item => {
          if (this.isMonth === 1) {
            this.calendarOptions.events.push({
              title: item.agriName ? item.agriName : '',
              start: item.startTime,
              ...item,
              fisrtDay: item.startTime,
              allDay: false
            })
            return true
          }
          if (item.startTime === item.endTime) {
            this.calendarOptions.events.push({
              title: item.agriName ? item.agriName : '',
              start: item.startTime,
              lastDay: item.endTime,
              ...item,
              fisrtDay: item.startTime,
              allDay: false
            })
          } else {
            const daysList = this.getDatesInRange(item.startTime, item.endTime)
            daysList.map(row => {
              this.calendarOptions.events.push({
                title: item.agriName ? item.agriName : '',
                start: row,
                fisrtDay: item.startTime,
                lastDay: item.endTime,
                id: item.id,
                ...item,
                allDay: false
              })
            })
          }
        })
        this.removeDuplicateEvents()
      })
    },
    // 数组去重
    removeDuplicateEvents () {
      const uniqueEvents = []
      const seenStarts = new Set()
      this.calendarOptions.events.forEach(event => {
        if (!seenStarts.has(event.start)) {
          seenStarts.add(event.start)
          uniqueEvents.push(event)
        }
      })
      this.calendarOptions.events = uniqueEvents
      this.showFef = true
    },
    getDatesInRange (startDate, endDate) {
      const daysList = []
      const SDate = this.$moment(startDate)
      const EDate = this.$moment(endDate)
      daysList.push(SDate.format('YYYY-MM-DD'))
      while (SDate.add(1, 'days').isBefore(EDate)) {
        daysList.push(SDate.format('YYYY-MM-DD'))
      }
      daysList.push(EDate.format('YYYY-MM-DD'))
      return daysList
    },
    // 新增事项
    addDate (content) {
      this.$refs.add.getData(content)
    },
    leftDay (type) {
      console.log(this.selectDate)
      if (type === 1 && this.isMonth === 1) {
        this.selectDate = this.$moment(this.selectDate).subtract(1, 'years').format('YYYY')
      }
      if (type === 2 && this.isMonth === 1) {
        this.selectDate = this.$moment(this.selectDate).add(1, 'years').format('YYYY')
      }
      if (type === 1 && this.isMonth === 0) {
        this.selectDate = this.$moment(this.selectDate).subtract(1, 'months').format('YYYY-MM')
      }
      if (type === 2 && this.isMonth === 0) {
        this.selectDate = this.$moment(this.selectDate).add(1, 'months').format('YYYY-MM')
      }
      console.log(this.selectDate)
      this.changeMonth()
    },
    // 日期修改
    changeDate () {
      // 选择想查看的日期，以及该日期下的任务。
      clearTimeout(this.setTime)
      this.setTime = setTimeout(() => {
        this.$nextTick(() => {
          if (this.isMonth === 0) {
            setTimeout(() => {
              this.$refs.fullCalendar.getApi().gotoDate(this.$moment(this.selectDate).format('YYYY-MM'))
            }, 1000)
          }
          this.$parent.changeMonth(this.selectDate)
        })
      }, 100)
    },
    // 点击月份
    changeMonth () {
      let selectDate = null
      if (this.isMonth === 1) {
        selectDate = `${this.$moment(this.selectDate).format('YYYY')}-${this.nowMonthSelct}`
      } else {
        selectDate = `${this.$moment(this.selectDate).format('YYYY-MM')}`
      }
      this.$parent.changeMonth(selectDate)
    },
    moreClick (content) {
      getAgriplanListApi({ startTime: this.$moment(content.date).format('YYYY-MM-DD'), endTime: this.$moment(content.date).format('YYYY-MM-DD') }).then(res => {
        this.moreList = res.data
        this.moreDate = {
          week: this.$moment(content.date).day(),
          day: content.date
        }
        this.dialogVisible = true
      })
    },
    // 点击事件
    eventClick (event) {

    },
    // 点击当天
    dayClick (day) {
      this.clickDay = day.dateStr
      this.$parent.changeDay(this.clickDay)
    }
  }
}
</script>
<style lang="scss" scoped>
  .fullcalendar {
    width: 90%;
    margin: 0 auto;
    padding: 0.1rem 0 0 0;
    box-sizing: border-box;
    background: #fff;
    border-radius: 0.2rem;
  }
  ::v-deep .fc-theme-standard .fc-scrollgrid {
    border: none
  }
  ::v-deep .fc-theme-standard td, .fc-theme-standard th {
    border: none
  }
  .back {
    font-size: 1.1542vw;
    margin-bottom: 1.5625vw * 0.834;
    width: 5.2083vw;
    cursor: pointer;
  }
  ::v-deep .fullcalendar {
    .fc-toolbar-chunk{
      > div {
        display: flex;
        align-items: center;
      }
    }
    .fc-header-toolbar {
      padding: 0 1rem 0 0.5rem
    }
    .fc-today-button {
      background: #FFFFFF;
      color: #333333;
      border-color: #DCDEDF;
      padding: 0.2em 0.9em;
    }
    .fc-prev-button {
      background: #FFFFFF;
      color: #333333;
      border: none
    }
    .fc-next-button {
      background: #FFFFFF;
      color: #333333;
      border: none
    }
    .fc-daygrid-event-dot {
      border-color: #19B560;
    }
    .fc-h-event {
      background-color: #E8F7EF;
      border-color: #E8F7EF;
      .eventBorder {
        opacity: 0
      }
      .eventContent {
        color:#19B560 !important
      }
    }
    .fc-toolbar-title {
      color: #333333;
      font-size: 0.2rem;
      margin: 0 0.02rem 0 0.25rem
    }
    .fc-button-primary:focus {
      box-shadow: none;
    }
    .fc-button-primary:active {
      box-shadow: unset !important;
      background-color: unset !important;
      color: #333333;
    }
    .fc-button-active:focus {
      box-shadow: none !important;
    }
    .fc-dayGridMonth-button, .fc-timeGridDay-button {
      background: #EDF1F4;
      color: #333333;
      border-color: #DCDEDF;
    }
    .fc-button-active {
      background-color: #FFFFFF !important;
      color: #333333 !important;
      border-color: #DCDEDF !important;
    }
    .fc-col-header-cell {
      .fc-scrollgrid-sync-inner {
        // background: #F6F8F9;
        padding: 0.1rem 0 0.2rem 0;
        color: #999;
        font-weight: 500;
      }
    }
    .fc .fc-daygrid-day.fc-day-today{
      background-color: unset;
      .dayHeight {
        border: 1px solid #00C586;
        color: #00C586
      }
    }
    .fc-theme-standard td, .fc-theme-standard th {
      border: none
    }
    .fc-daygrid-day-top  {
      display: block;
    }
    .dayFlex {
      // padding: 0 0.1rem;
      display: flex;
      align-items: center;
      width: 100%;
      // height: 0.35rem;
      justify-content: center;
    }
    .fc-daygrid-day-number {
      padding: 0;
      display: flex;
      align-items: center;
      line-height: 1;
      justify-content: center
    }
    .dayAdd {
      width: 0.25rem;
      height: 0.25rem
    }
    .dayHeight {
      width: 22px;
      height: 21px;
      line-height: 21px;
      text-align: center;
      color: #333333;
      border-radius: 2px;
    }
    .checkDay {
      background: #00C586;
      color: #fff !important;
      border-radius: 2px;
    }
    .fc-daygrid-day-events {
      padding: 0 0.1rem
    }
    .fc-more-popover {
      z-index: -9999;
    }
  }
  .nowMonthHas {
    border: 1px solid #00C586;
    color: #00C586
  }
  .greyColor {
    color: #666;
  }
  .editClass {
  ::v-deep  .el-dialog__header {
      display: none;
    }
  }
  .eventContent {
    display: flex;
    align-items: center;
    justify-content: center;
    .eventBorder {
      background: #19B560;
      width: 0.05rem;
      height: 0.05rem;
      border-radius: 50%;
      // margin-right: 0.05rem
    }
  }
  .dayBottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 0.2rem;
    .dayImg {
      display: flex;
      align-items: flex-end;
      .dayHeight {
        font-weight: bold;
        font-size: 0.24rem;
        span {
          font-size: 0.2rem;
        }
      }
      img {
        width: 0.25rem;
        margin-left: 0.1rem
      }
    }
    .wordImg {
      width: 0.36rem;
    }
    .el-icon-close {
      font-size: 0.28rem;
      color: #000
    }
  }
  .mt15 {
    margin-top: 0.1rem
  }
  .dayDetail {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .dayHeight {
      border-left: 0.05rem solid #19B560;
      padding-left: 0.08rem;
      line-height: 100%;
      font-size: 0.24rem;
    }
    .wordImg {
      img {
        width: 0.36rem;
      }
    }
  }
  .dayDetailContent {
    .eventBorder {
      width: 0.2rem !important;
      height: 0.2rem !important;
      margin: 0 0.07rem
    }
    .eventContent {
      margin-top: 0;
      img {
        width: 0.36rem;
      }
    }
  }
  .selectBox {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 0.35rem;
    font-size: 12px;
    .monthDay {
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #E0E2E4;
      span {
        padding: 0.02rem 0.1rem;
        border-radius: 0.01rem;
      }
      .checkDayChange {
        border:1px solid #00C586;
        color: #00C586;
      }
    }
    .searchInput {
      width: 10rem;
    }
    .selectMonth {
      display: flex;
      align-items: center;
      font-size: 0.2rem;
      font-weight: bold;
      height: 26px;
      border: 1px solid #E0E2E4;
      // .el-icon-arrow-left {
        // margin-right: 0.1rem;
      // }
      ::v-deep .el-date-editor {
        width: 70px;
        height: 25px;
        line-height: 25px;
        border-left: 1px solid #E0E2E4;
        border-right: 1px solid #E0E2E4;
        .el-input__inner {
          border: none;
          height: auto;
          line-height: unset;
          padding-left: 0;
          padding-right: 0;
          text-align: center;
          background: unset;
        }
        .el-input__prefix {
          display: none
        }
      }
      > i {
        padding: 0 3px;
        line-height: 1;
      }
    }
  }
  .monthLine {
    margin-top: 0.2rem;
    font-size: 0.18rem;
    .monthText {
      width: 14.2857%;
      margin-bottom: 6px;
      > span {
        width: 22px;
        height: 21px;
        line-height: 21px;
        border-radius: 2px;
        display: inline-block;
        margin-bottom: 2px;
      }
      // display: flex;
      align-items: center;
      text-align: center;
      justify-content: center;
    }
  }
  .monthTag {
    padding: 0 0.2rem;
    height: 67vh;
    overflow-y: auto;
  }
  .tagFlex {
    display: flex;
    padding: 0.2rem 0;
    width: calc(100% - 0.4rem);
    border-bottom: 1px solid #ccc;
    .tagTime {
      font-size: 0.18rem;
      font-weight: bold;
      margin-right: 0.2rem
    }
    .tagTitle {
      display: flex;
      align-items: center;
      span {
        width: 0.15rem;
        height: 0.15rem;
        border-radius: 0.02rem;
        margin-right: 0.05rem;
        background: #19B560;
      }
    }
    .greyColor {
      color: #999;
      margin-top: 0.15rem;
      span {
        margin-left: 0.15rem;
      }
    }
  }
  .nowMonthSelct {
    color: #fff;
    background: #19B560;
    width: 22px;
    height: 21px;
    line-height: 21px;
    border-radius: 2px;
  }
  .divWidth {
    width: 100%;
  }
</style>
